﻿#region Librerias

using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.Text;
using ESF.General;
using System.IO;
using ESF.WCF;

#endregion


namespace ESF.SFT.FileReplicator
{
	[ExceptionBehaviorAttribute]
	public class FileReplicator : IFileReplicator
	{
		public void Copy(FileUploadCopyMessage pFileUploadMessage)
		{
			string destinationFolder;
			string destinationFileName;
			string backupDestinationFileName;


			destinationFolder = ReadConfig.GetAppSetting ("Destination." + pFileUploadMessage.Destination);

			FileHelper.EnsureFolder (destinationFolder);

			destinationFileName = Path.Combine (destinationFolder, Path.GetFileName (pFileUploadMessage.Name));

			
			destinationFolder = Path.Combine (ReadConfig.GetAppSetting("DestinationBackup." + pFileUploadMessage.Destination), pFileUploadMessage.FolderPath);

			FileHelper.EnsureFolder(destinationFolder);

			backupDestinationFileName = Path.Combine (destinationFolder,
				string.Format("{0}_{1}{2}",
					FileHelper.GetFileNameFirstPoint(pFileUploadMessage.Name), Guid.NewGuid().ToString(), FileHelper.GetFileNameExtensionFromFirstPoint (pFileUploadMessage.Name))
				);


			using (FileStream writer = new FileStream(backupDestinationFileName, FileMode.Create))
			{
				pFileUploadMessage.FileUploadContent.CopyTo(writer);
			}

			FileHelper.Copy (backupDestinationFileName, destinationFileName);
		}
	}
}